<!--
  注册页面
-->
<template>
  <div class="register-container">
    <div class="register-card">
      <!-- Logo和标题 -->
      <div class="register-header">
        <el-icon size="48" class="logo">
          <Document />
        </el-icon>
        <h1 class="title">用户注册</h1>
        <p class="subtitle">创建您的AI-SOES账号</p>
      </div>

      <!-- 注册表单 -->
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        size="large"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="用户名"
            prefix-icon="User"
            clearable
            autocomplete="username"
          />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            type="email"
            placeholder="邮箱地址"
            prefix-icon="Message"
            clearable
            autocomplete="email"
          />
        </el-form-item>

        <el-form-item prop="role">
          <el-select
            v-model="registerForm.role"
            placeholder="选择用户角色"
            style="width: 100%"
          >
            <el-option
              label="学生"
              value="student"
            />
            <el-option
              label="教师"
              value="teacher"
            />
            <el-option
              label="管理员"
              value="admin"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>

        <el-form-item prop="confirm_password">
          <el-input
            v-model="registerForm.confirm_password"
            type="password"
            placeholder="确认密码"
            prefix-icon="Lock"
            show-password
            autocomplete="new-password"
            @keyup.enter="handleRegister"
          />
        </el-form-item>

        <el-form-item prop="student_id" v-if="registerForm.role === 'student'">
          <el-input
            v-model="registerForm.student_id"
            placeholder="学号"
            prefix-icon="Postcard"
            clearable
          />
        </el-form-item>

        <el-form-item prop="real_name" v-if="registerForm.role !== 'admin'">
          <el-input
            v-model="registerForm.real_name"
            placeholder="真实姓名"
            prefix-icon="UserFilled"
            clearable
          />
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="手机号码（可选）"
            prefix-icon="Phone"
            clearable
          />
        </el-form-item>

        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-link type="primary" @click="showTerms">用户协议</el-link>
            和
            <el-link type="primary" @click="showPrivacy">隐私政策</el-link>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="authStore.loading"
            @click="handleRegister"
            class="register-btn"
          >
            注册账号
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 返回登录 -->
      <div class="back-to-login">
        <span>已有账号？</span>
        <el-button
          text
          type="primary"
          @click="handleBackToLogin"
        >
          立即登录
        </el-button>
      </div>
    </div>

    <!-- 版权信息 -->
    <div class="copyright">
      <p>&copy; 2025 AI-SOES. All rights reserved.</p>
    </div>

    <!-- 用户协议对话框 -->
    <el-dialog
      v-model="termsDialogVisible"
      title="用户协议"
      width="600px"
      max-height="70vh"
    >
      <div class="terms-content">
        <h3>AI-SOES用户服务协议</h3>
        <p>欢迎使用AI-SOES智能在线考试系统...</p>
        <!-- 这里可以放置完整的用户协议内容 -->
      </div>
      <template #footer>
        <el-button type="primary" @click="termsDialogVisible = false">
          我已了解
        </el-button>
      </template>
    </el-dialog>

    <!-- 隐私政策对话框 -->
    <el-dialog
      v-model="privacyDialogVisible"
      title="隐私政策"
      width="600px"
      max-height="70vh"
    >
      <div class="privacy-content">
        <h3>AI-SOES隐私政策</h3>
        <p>我们非常重视您的隐私保护...</p>
        <!-- 这里可以放置完整的隐私政策内容 -->
      </div>
      <template #footer>
        <el-button type="primary" @click="privacyDialogVisible = false">
          我已了解
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useAuthStore } from '@/stores'
import type { RegisterFormData } from '@/types'
import { Document } from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

const registerFormRef = ref<FormInstance>()
const termsDialogVisible = ref(false)
const privacyDialogVisible = ref(false)

// 注册表单数据
const registerForm = reactive<RegisterFormData & {
  confirm_password: string
  agreement: boolean
}>({
  username: '',
  email: '',
  password: '',
  confirm_password: '',
  role: 'student',
  student_id: '',
  real_name: '',
  phone: '',
  agreement: false
})

// 密码验证函数
const validatePassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'))
  } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
    callback(new Error('密码必须包含大小写字母和数字'))
  } else {
    callback()
  }
}

// 确认密码验证函数
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 邮箱验证函数
const validateEmail = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入邮箱地址'))
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirm_password: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  student_id: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  real_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  agreement: [
    { required: true, message: '请阅读并同意用户协议和隐私政策', trigger: 'change' }
  ]
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    await authStore.registerAction({
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      role: registerForm.role,
      student_id: registerForm.student_id,
      real_name: registerForm.real_name,
      phone: registerForm.phone
    })

    // 注册成功后跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('Register error:', error)
  }
}

// 返回登录页
const handleBackToLogin = () => {
  router.push('/login')
}

// 显示用户协议
const showTerms = () => {
  termsDialogVisible.value = true
}

// 显示隐私政策
const showPrivacy = () => {
  privacyDialogVisible.value = true
}
</script>

<style scoped lang="scss">
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;

  .register-card {
    width: 100%;
    max-width: 480px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
    padding: 40px;
    margin-bottom: 20px;

    .register-header {
      text-align: center;
      margin-bottom: 30px;

      .logo {
        color: var(--el-color-primary);
        margin-bottom: 16px;
      }

      .title {
        font-size: 28px;
        font-weight: bold;
        color: var(--el-text-color-primary);
        margin: 0 0 8px 0;
      }

      .subtitle {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin: 0;
      }
    }

    .register-form {
      .register-btn {
        width: 100%;
        height: 48px;
        font-size: 16px;
        font-weight: 500;
      }
    }

    .back-to-login {
      text-align: center;
      margin-top: 24px;

      span {
        color: var(--el-text-color-regular);
        margin-right: 8px;
      }
    }
  }

  .copyright {
    text-align: center;
    color: rgba(255, 255, 255, 0.8);
    font-size: 14px;

    p {
      margin: 0;
    }
  }
}

// 对话框内容样式
.terms-content,
.privacy-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px 0;

  h3 {
    color: var(--el-text-color-primary);
    margin-bottom: 16px;
  }

  p {
    line-height: 1.6;
    color: var(--el-text-color-regular);
    margin-bottom: 12px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .register-container {
    padding: 16px;

    .register-card {
      padding: 30px 24px;

      .register-header {
        margin-bottom: 24px;

        .title {
          font-size: 24px;
        }
      }
    }
  }
}

// 暗色主题适配
[data-theme="dark"] {
  .register-container {
    background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);

    .register-card {
      background: var(--el-bg-color);
      box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
    }
  }
}
</style>